import '../../../main.js';
import 'bootstrap';
import DataTable from 'datatables.net-dt';
import $ from 'jquery';
import { NotificationManager } from '/src/util/notification/notification.js'

import { ActuatorService } from '/src/api/actuator.js'

let tableStructureData;

let cacheTableStructureData = [];

let selectConnectionIdList = [];

function initClickEvent() {
    $('#load').on('click', handleLoad)
    $('#execute').on('click', handleExecute)
    $('#cancel').on('click', handleCancel)
}

function initTabelStructureSelected() {
    $('#tabelStructureSelected').empty(); // 清空

    // 默认选项
    ActuatorService.loadTableStructure().then(res => {
        tableStructureData = res;
        Object.keys(res).forEach(key => {
            $('#tabelStructureSelected').append(new Option(res[key].comment ? res[key].comment : key, key));
        });
    });
}

function handleLoad() {
    const select = document.getElementById('tabelStructureSelected');
    const selectedTable = select.value;

    if (cacheTableStructureData.length != 0 &&
        cacheTableStructureData.filter(t => t.table == selectedTable).length != 0) {
        return;
    }

    const tableId = selectedTable + '-table';
    let data = getTableStructureData(selectedTable);
    let rawData = data['structure'];

    cacheTableStructureData.push(data)

    $('#tables').append(generateTable(tableId, selectedTable));
    $(`#${tableId}-button`).on('click', function () {
        deleteTable(`${tableId}-div`)
    })

    $('#' + tableId).DataTable({
        data: rawData,
        paging: false,       // 禁用分页
        searching: false,    // 禁用全局搜索
        lengthChange: false, // 禁用每页显示条数选择器
        info: false,         // 禁用底部信息栏
        columns: [
            { data: 'columnName', title: '字段名' },
            {
                data: 'columnComment',
                title: '注释',
                defaultContent: '-'
            },
            {
                data: 'DisplayMethods',
                title: '展示方式',
                render: function (data, type, row) {
                    return `
                    <select class="form-select form-select-sm" data-field="${row.columnName}" data-config="display">
                    <option value="">请选择</option>
                    <option value="COUNT()" ${data === 'COUNT()' ? 'selected' : ''}>统计</option>
                    <option value="SUM()" ${data === 'SUM()' ? 'selected' : ''}>求和</option>
                    </select>`;
                }
            },

            // 聚合方式（PolymerizationMode）
            {
                data: 'PolymerizationMode',
                title: '聚合方式',
                render: function (data, type, row) {
                    return `
                    <select class="form-select form-select-sm" data-field="${row.columnName}" data-config="polymerization">
                    <option value="">无</option>
                    <option value="DATE()" ${data === 'DATE()' ? 'selected' : ''}>日期</option>
                    <option value="EMPTY()" ${data === 'EMPTY()' ? 'selected' : ''}>本值</option>
                    </select>`;
                }
            },

            // 过滤方式（ScreenMode）
            {
                data: 'ScreenMode',
                title: '过滤方式',
                render: function (data, type, row) {
                    return `
                    <select class="form-select form-select-sm" data-field="${row.columnName}" data-config="screen">
                    <option value="">无</option>
                    <option value="DATE()" ${data === 'DATE()' ? 'selected' : ''}>日期</option>
                    <option value="LIKE()" ${data === 'LIKE()' ? 'selected' : ''}>相似</option>
                    </select>`;
                }
            },

            // 排序方式（Sort）
            {
                data: 'Sort',
                title: '排序方式',
                render: function (data, type, row) {
                    return `
                    <select class="form-select form-select-sm" data-field="${row.columnName}" data-config="sort">
                    <option value="">无</option>
                    <option value="asc" ${data === 'asc' ? 'selected' : ''}>升序</option>
                    <option value="desc" ${data === 'desc' ? 'selected' : ''}>降序</option>
                    </select>`;
                }
            },

            // 连接方式（Connection）
            {
                data: 'Connection',
                title: '连接方式',
                render: function (data, type, row) {
                    var id = `select-${row.columnName}-${tableId}-connection`;
                    selectConnectionIdList.push(id);

                    return `
                    <select id='${id}' class="form-select form-select-sm" data-field="${row.columnName}" data-config="connection">
                    <option value="">无</option>
                    </select>`;
                }
            },

            // 是否是X轴数据 (IsXaxis)
            {
                data: 'IsXaxis', // 假设你的数据模型中有这个字段来存储状态
                title: 'X轴',
                orderable: false, // 通常X轴选择列不需要排序
                render: function (data, type, row) {
                    // 为每个开关生成唯一的ID，方便后续可能的事件绑定
                    const switchId = `xaxis-switch-${row.columnName}-${tableId}`;
                    var isChecked = 0;

                    return `
                    <div class="form-check form-switch d-flex justify-content-center">
                        <input class="form-check-input" type="checkbox" role="switch" 
                            id="${switchId}" 
                            data-field="${row.columnName}" 
                            data-config="xaxis"
                            ${isChecked ? 'checked' : ''}>
                    </div>`;
                }
            }
        ],
        initComplete: function (settings, json) {
            generateTableConnection();
        }
    });
}

function generateTableConnection() {
    // 清空之前可能存在的 ID 列表
    selectConnectionIdList = [];

    // 遍历所有已添加的表结构数据
    cacheTableStructureData.forEach(tableData => {
        const currentTableName = tableData.table;
        const tableId = currentTableName + '-table';

        // 获取当前表的 DataTable 实例
        const $table = $('#' + tableId);
        if ($table.length > 0) {
            const dataTable = $table.DataTable();

            // 遍历当前表的每一行（每个字段）
            dataTable.rows().every(function (rowIdx) {
                const rowData = this.data();
                const fieldName = rowData.columnName;
                const selectId = `select-${fieldName}-${tableId}-connection`;

                // 将当前 select 的 ID 添加到列表中，方便后续查找
                selectConnectionIdList.push(selectId);

                // 找到对应的 select 元素
                const $select = $(`#${selectId}`);
                if ($select.length > 0) {
                    // 清空现有选项（除了"无"）
                    $select.empty().append('<option value="">无</option>');

                    // 遍历所有已缓存的表结构，找出不是当前表的字段
                    cacheTableStructureData.forEach(otherTableData => {
                        const otherTableName = otherTableData.comment || otherTableData.table;

                        // 排除当前表自身
                        if (otherTableData.table !== currentTableName) {
                            // 遍历其他表的字段列表
                            otherTableData.structure.forEach(column => {
                                const otherFieldName = column.columnName;
                                const otherFieldComment = column.columnComment || otherFieldName;
                                const optionValue = `${otherTableData.table}.${otherFieldName}`;
                                const optionText = `${otherTableName}.${otherFieldComment}`;
                                // 添加选项
                                $select.append(`<option value="${optionValue}">${optionText}</option>`);
                            });
                        }
                    });

                    // 如果原始数据中有 Connection 值，则设置选中项
                    if (rowData.Connection) {
                        $select.val(rowData.Connection);
                    }
                }
            });
        }
    });
}

function handleCancel() {
    tableStructureData = {}
    cacheTableStructureData = []
    selectConnectionIdList = []
}

function handleExecute() {
    var data = exportTableData()

    if (!data) {
        NotificationManager.error('无数据');
    }

    ActuatorService.createSQL(data).then(res => {
        if (window.modalCallback) {
            window.modalCallback({
                'searchBar': convertToFilterString(data),
                'sql': res
            });
        }
    })
}

function exportTableData() {
    const result = {};

    // 找到所有 id 以 '-table' 结尾的 <table> 元素
    $('table[id$="-table"]').each(function () {
        const $table = $(this);
        const tableId = $table.attr('id');
        const tableName = tableId.replace('-table', ''); // 提取表名

        // 初始化该表的配置
        result[tableName] = {};

        // 获取 DataTable 实例
        const dataTable = $table.DataTable();

        // 遍历该表的每一行
        dataTable.rows().every(function () {
            const data = this.data();           // 原始数据行
            const rowNode = this.node();        // 当前行的 DOM 节点
            const fieldName = data.columnName;
            const columnComment = data.columnComment;

            result[tableName][fieldName] = {};

            // 读取三个下拉框的值
            const displayValue = $(rowNode).find('select[data-config="display"]').val();
            const polymerizationValue = $(rowNode).find('select[data-config="polymerization"]').val();
            const screenValue = $(rowNode).find('select[data-config="screen"]').val();
            const sortValue = $(rowNode).find('select[data-config="sort"]').val();
            const connectionValue = $(rowNode).find('select[data-config="connection"]').val();
            const xAxisValue = $(rowNode).find('input[data-config="xaxis"]').is(':checked');

            // 只有非空值才写入
            if (displayValue) {
                result[tableName][fieldName].DisplayMethods = displayValue;
            }
            if (polymerizationValue) {
                result[tableName][fieldName].PolymerizationMode = polymerizationValue;
            }
            if (screenValue) {
                result[tableName][fieldName].ScreenMode = screenValue;
            }
            if (sortValue) {
                result[tableName][fieldName].Sort = sortValue;
            }
            if (connectionValue) {
                result[tableName][fieldName].Connection = connectionValue;
            }
            if (xAxisValue !== null) {
                result[tableName][fieldName].IsXaxis = xAxisValue;
            }
            if (columnComment) {
                result[tableName][fieldName].ColumnComment = columnComment;
            }

            // 清理空对象
            if (Object.keys(result[tableName][fieldName]).length === 0) {
                delete result[tableName][fieldName];
            }
        });

        // 如果该表没有任何字段配置，清理
        if (Object.keys(result[tableName]).length === 0) {
            delete result[tableName];
        }
    });

    return result;
}

function convertToFilterString(inputObj) {
    const result = [];

    // 遍历对象的每个属性
    for (const [tableName, fields] of Object.entries(inputObj)) {
        for (const [field, mode] of Object.entries(fields)) {
            switch (mode['ScreenMode']) {
                case 'DATE()':
                    result.push('date')
                    break;
                case 'LIKE()':
                    var temp = mode['ColumnComment'] ? mode['ColumnComment'] : field
                    result.push(`input-${tableName}.${field}-${temp}`)
                    break;
            }
        }
    }

    return result.join(',');
}

function getTableStructureData(selectedTable) {
    let data;
    Object.keys(tableStructureData).forEach(res => {
        if (selectedTable == res) {
            data = {
                'table': res,
                'comment': tableStructureData[selectedTable]['comment'],
                'structure': tableStructureData[selectedTable]['columnList']
            }
            return;
        }
    });

    return data;
}

function generateTable(id, title) {
    return `
    <div id="${id}-div" class="generated-table-container mb-4">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <h6 class="m-0 text-primary">${title}</h6>
        <button id="${id}-button" type="button" 
            class="btn btn-sm btn-outline-danger delete-table" data-table-id="${id}">
          删除 ×
        </button>
      </div>
      <div class="table-responsive">
        <table id="${id}" class="table table-striped table-hover" style="width: 100%"></table>
      </div>
    </div>
  `;
}

function deleteTable(id) {
    $('#' + id).remove()
    cacheTableStructureData = cacheTableStructureData.filter(item => item.table !== id.split('-')[0]);
}

export function init() {
    $(document).ready(function () {
        initClickEvent();
        initTabelStructureSelected();
    });
}